package com.jiandp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiandp.dto.Result;
import com.jiandp.dto.ScrollResult;
import com.jiandp.dto.UserDTO;
import com.jiandp.entity.Blog;
import com.jiandp.entity.Follow;
import com.jiandp.entity.User;
import com.jiandp.mapper.BlogMapper;
import com.jiandp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiandp.service.IFollowService;
import com.jiandp.service.IUserService;
import com.jiandp.utils.SystemConstants;
import com.jiandp.utils.UserHolder;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.jiandp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.jiandp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
           this.queryBlogUser(blog);
           this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //根据id查询blog
        Blog blog = getById(id);
        if (blog==null){
            return Result.fail("博客不存在");
        }
        //查询博客相关的用户
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user==null){
            return;
        }
        //获取登录用户
        Long userId = user.getId();

        //判断当前用户是否点赞
        String key = BLOG_LIKED_KEY+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登录用户
        Long userId = UserHolder.getUser().getId();

        //判断当前用户是否点赞
        String key = BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score==null){
            //如果未点赞 可以点赞
            //修改数据库并+1
            boolean ifSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            if (ifSuccess){
                //保存用户信息到redis中的set集合
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }


        }else {
            //如果已经点赞 取消点赞
            //修改数据库并-1
            boolean ifSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            if (ifSuccess){
                //移除redis中的用户信息
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }


        }
        return Result.ok();

    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY+id;
        //查询top5的点赞用户
        Set<String> ids = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        String idStr = StrUtil.join(",", ids);
        if (ids==null||ids.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<UserDTO> userDTOS = userService.query().in("id",ids)
                .last("ORDER BY FIELD(id,"+idStr+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {

        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("笔记不存在");
        }
        //查询关注的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //获取粉丝id并推送
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = FEED_KEY +userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }


        // 返回id
        return Result.ok(blog.getId());

    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //查询收件箱
        String key = FEED_KEY +userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        //解析数据
        List<Long> ids =new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;

        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if (time==minTime){
                os++;
            }else {
                minTime=time;
                os=1;
            }

        }

        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            //查询博客相关的用户
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(offset);
        r.setMinTime(minTime);


        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
